package jodd.http;

import archer.framework.protocol.ArcherProtocolModule;
import archer.framework.test.support.TestConfig;
import archer.framework.utils.JSONUtils;
import jodd.util.StringPool;
import jodd.util.StringUtil;

import java.io.*;
import java.util.Map;

/**
 * 调试用途的HttpRequest
 *
 * @author christ
 * @date 2015/7/21
 */
public class HttpResponseForDebug extends HttpResponse {

    /**
     * Reads response input stream and returns {@link HttpResponse response}.
     * Supports both streamed and chunked response.
     */
    public static HttpResponse readFrom(InputStream in) {
        InputStreamReader inputStreamReader;
        try {
            inputStreamReader = new InputStreamReader(in, StringPool.ISO_8859_1);
        } catch (UnsupportedEncodingException ignore) {
            return null;
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);

        HttpResponse httpResponse = new HttpResponseForDebug();

        // the first line
        String line;
        try {
            line = reader.readLine();
        } catch (IOException ioex) {
            throw new HttpException(ioex);
        }

        if (line != null) {

            line = line.trim();

            int ndx = line.indexOf(' ');
            httpResponse.httpVersion(line.substring(0, ndx));

            int ndx2 = line.indexOf(' ', ndx + 1);
            if (ndx2 == -1) {
                ndx2 = line.length();
            }
            httpResponse.statusCode(Integer.parseInt(line.substring(ndx, ndx2).trim()));

            httpResponse.statusPhrase(line.substring(ndx2).trim());
        }

        httpResponse.readHeaders(reader);
        httpResponse.readBody(reader);

        return httpResponse;
    }

    @Override
    public String bodyText() {

        System.out.println("<<==================================================================");
        System.out.println(super.bodyText());

        return super.bodyText();
    }

    public HttpResponseForDebug cacheToken() {

        try {

            String s = super.bodyText();
            Map result = JSONUtils.deserialize(s, Map.class);
            Map data = (Map) result.get("resultData");
            String token = (String) data.get(ArcherProtocolModule.tokenField);
            TestConfig.cacheToken(token);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return this;
    }

    public String toString() {
        String s = StringUtil.convertCharset(super.toString(), StringPool.ISO_8859_1, StringPool.UTF_8);
        System.out.println("<<==================================================================");
        System.out.println(s);
        return s;
    }
}
